package cn.zc.interceptor;
import cn.zc.context.UserContext;
import cn.zc.entity.User;
import cn.zc.mapper.LoginMapper;
import cn.zc.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private LoginMapper loginMapperl;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String id = request.getParameter("id");
        String password = request.getParameter("password");
        User user1 = new User();
        user1.setId(id);
        user1.setMypassword(password);
        User loginuser = loginMapperl.login(user1);
        // 获取User-Agent头信息
        String userAgent = request.getHeader("User-Agent");
        String browserName = getBrowserName(userAgent);
        if (browserName.equals("Unknown")){
            response.getWriter().write("-2");
            response.setStatus(401);
            return false;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getStudentTokenName());
        String userid = request.getHeader("userid");
        //用户名或者密码错误
        if (loginMapperl.login(user1)==null){
            response.getWriter().write("-1");
            response.setStatus(401);
            return false;
        }
        //判断是否为第一次登录
        if(loginuser.getIsonelogin()==1){
            UserContext.setUser(loginuser.getId());
            //第一次登录，更新浏览器信息
            loginMapperl.updateonebrowser(loginuser.getId(),browserName);
            return true;
        }
        //2、校验令牌
        try {
            //判断浏览器是否为第一次使用的
            if (!browserName.equals(loginuser.getOnebrowser())){
                response.setStatus(401);
                response.getWriter().write("-5");
                return false;
            }
            if (token == null|| token.isEmpty()||token.equals("null")){
                response.setStatus(401);//TODO 密钥失效，请联系管理员
                response.getWriter().write("-3");
                return false;
            }
            if (!loginuser.getUuid().equals(token)){
                response.getWriter().write("-4");
                response.setStatus(401);//TODO 禁止一台设备登录两个账号
                return false;
            }
            //将当前操作的员工id设置到BaseContext中
            UserContext.setUser(loginuser.getId());
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
    private String getBrowserName(String userAgent) {
        if (userAgent.contains("Chrome")) {
            return "Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Firefox";
        } else if (userAgent.contains("Safari")) {
            return "Safari";
        } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            return "Internet Explorer";
        } else {
            return "Unknown";
        }
    }
}